package com.whq.thrift.api.web.admin.service.job;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.whq.thrift.api.common.constants.CommonConfigConstants;
import com.whq.thrift.api.web.admin.db.requestlog.RequestLog;
import com.whq.thrift.api.web.admin.service.requestlog.RequestLogService;

/**
 * 按小时统计requestlog数据
 * 
 * @author v.qiuzhipin
 * 
 */
@Service
public class StatRequestHourApiDataJob {
	private static final Logger LOGGER = LoggerFactory.getLogger(MonitorConsumeLogInfoJob.class);
	private static final Logger LOGGER_QUARTZ = LoggerFactory.getLogger(CommonConfigConstants.LOGGER_KEY_QUARTZ);

	@Autowired
	private RequestLogService requestLogService;

	public void statRequestHourApiData() {
		LOGGER_QUARTZ.info("begin stat requestlog hour info data");

		// 获取当前时间日期
		long currentTimeMillis = System.currentTimeMillis();

		Date currentDate = new Date(currentTimeMillis);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		//获取每个小时的整点时间
		Calendar currentCalender = Calendar.getInstance();
		currentCalender.setTime(currentDate);
		currentCalender.set(Calendar.SECOND, 0);
		currentCalender.set(Calendar.MINUTE, 0);
		Date currentTime = currentCalender.getTime();

		long duringMillis = currentTime.getTime() - (60l * 60l * 1000l);
		Date duringDate = new Date(duringMillis);

		String startTime = format.format(duringDate);
		String statDay = sdf.format(duringDate);
		String endTime = format.format(currentTime);

		// 获取当前requestLog的具体数据表
		RequestLog requestLog = new RequestLog();
		requestLog.setTime(duringDate);
		int tableSeq = requestLog.getTableSeq();

		// 获取查询数据所在的小时
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(duringDate);
		int statHour = calendar.get(Calendar.HOUR_OF_DAY);

		try {
			this.requestLogService.replaceStatHourApiData(tableSeq, statDay, startTime, endTime, statHour);
		} catch (Exception e) {
			LOGGER.error("replace hour requestLog exception", e);
		}

		long duMillis = System.currentTimeMillis() - currentTimeMillis;
		LOGGER_QUARTZ.info("end stat hour requestLog data [" + (duMillis / 1000) + "s]");
	}

}
